package com.chenxin.interact.handler.sapHandler;

import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.dto.SapSupplierDTO;
import com.chenxin.interact.domain.sapDetail.SapIsReq;
import com.chenxin.interact.domain.sapDetail.SupplierItData;
import com.chenxin.interact.domain.sapResponse.SapSupplierResponse;
import com.chenxin.wms.domain.SupplierEntity;
import com.chenxin.wms.service.ISupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.reactive.function.client.WebClient;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class SupplierRequest {
    @Autowired
    private ISupplierService supplierService;

    public void requestFromSap(UrlMap urlMap) {
        // 构建一个请求实体类DTO
        SapSupplierDTO supplierDTO = new SapSupplierDTO();
        // 构建请求头IS_REQ
        SapIsReq isReq = new SapIsReq();
        supplierDTO.setIS_REQ(isReq);
        // 构建WebClient
        WebClient client = WebClient.builder()
                .baseUrl(urlMap.getUrlAdr())
                .defaultHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader(urlMap.getUsername(), urlMap.getPassword()))
                .build();
        // 发送请求
        SapSupplierResponse response = client.post()
                .uri(urlMap.getUriAdr())
                .bodyValue(supplierDTO)
                .retrieve()
                .bodyToMono(SapSupplierResponse.class).block();
        // 处理响应
        assert response != null;
        // 将获取到的合作伙伴数据存入数据库
        List<SupplierItData.SupplierItem> suppliers = response.getItData().getItems();
        if (suppliers.size() > 0) {
            suppliers.forEach(supplier -> {
                SupplierEntity isExits = supplierService.selectSupplierBySupplierNo(supplier.getPARTNER());
                if (isExits == null) {
                    SupplierEntity supplierEntity = new SupplierEntity();
                    supplierEntity.setSupplierNo(supplier.getPARTNER());
                    supplierEntity.setSupplierName(supplier.getNAME());
                    supplierEntity.setSupplierType(supplier.getZTYPE());
                    supplierEntity.setIsActive(supplier.getSTATE());
                    supplierService.insertSupplier(supplierEntity);
                }
            });
        }
    }

    private String basicAuthHeader(String username, String password) {
        String auth = username + ":" + password;
        String encodedCredentials = Base64Utils.encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        return "Basic " + encodedCredentials;
    }
}
